package xpn.platform.modules.todo.todolink;

import java.io.UnsupportedEncodingException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xpn.platform.modules.sys.user.SysUser;
import xpn.platform.modules.sys.user.SysUserDAO;
import xpn.platform.modules.todo.common.BatchCreateRequestDTO;
import xpn.platform.modules.todo.donelink.DoneLink;
import xpn.platform.modules.todo.donelink.DoneLinkDAO;
import xpn.platform.modules.todo.wsdl.TodosCall;
import xpn.platform.modules.workflow.runtime.todo.Todo;
import xpn.platform.modules.workflow.runtime.todo.TodoDAO;

import com.google.common.base.Strings;

import lombok.extern.slf4j.Slf4j;

/**
 * 待办 服务实现类
 *
 * @author duwei
 */
@Slf4j
@Service
public class TodoServiceImpl implements TodoService {

    private final TodoLinkDAO todoLinkDAO;

    private final DoneLinkDAO doneLinkDAO;

    @Autowired
    TodoDAO todoDAO;

    @Autowired
    SysUserDAO sysUserDAO;

    @Autowired
    TodosCall todosCall;

    @Autowired
    public TodoServiceImpl(TodoLinkDAO todoLinkDAO, DoneLinkDAO doneLinkDAO) {
        this.todoLinkDAO = todoLinkDAO;
        this.doneLinkDAO = doneLinkDAO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void toDone(String taskId) {
        if (!Strings.isNullOrEmpty(taskId)) {
            TodoLink todoLink = todoLinkDAO.findByTaskId(taskId);
            if (todoLink != null) {
                DoneLink doneLink = createDoneLink(todoLink);
                doneLinkDAO.save(doneLink);
                todoLinkDAO.delete(todoLink);
                SysUser sendee = sysUserDAO.getOne(Long.parseLong(todoLink.getSendeeId()));
                /*try {
                    todosCall.complete(todoLink.getLinkUrl(), sendee.getUserCode());
                    log.info("连接多米诺平台完成TODO[" + todoLink.getSubject() + "]成功");
                } catch (RemoteException | UnsupportedEncodingException e) {
                    e.printStackTrace();
                    log.error("连接多米诺平台完成TODO[" + todoLink.getSubject() + "]失败", e);
                }*/
            }
        }
    }

    /**
     * 根据已办 创建待办
     *
     * @param todoLink
     */
    private DoneLink createDoneLink(TodoLink todoLink) {
        DoneLink doneLink = new DoneLink();
        BeanUtils.copyProperties(todoLink, doneLink, "id");
        return doneLink;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByTaskId(String taskId) {
        if (!Strings.isNullOrEmpty(taskId)) {
            TodoLink todoLink = todoLinkDAO.findByTaskId(taskId);
            if (todoLink != null) {
                SysUser sendee = sysUserDAO.getOne(Long.parseLong(todoLink.getSendeeId()));
                /*try {
                    todosCall.delete(todoLink.getLinkUrl(), sendee.getUserCode());
                    log.info("连接多米诺平台删除TODO[" + todoLink.getSubject() + "]成功");
                } catch (RemoteException | UnsupportedEncodingException e) {
                    e.printStackTrace();
                    log.error("连接多米诺平台删除TODO[" + todoLink.getSubject() + "]失败", e);
                }*/
                todoLinkDAO.delete(todoLink);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void batchToDone(String[] ids) {
        if (ids.length > 0) {
            for (String id : ids) {
                TodoLink todoLink = todoLinkDAO.getOne(Long.parseLong(id));
                if (todoLink != null) {
                    DoneLink doneLink = createDoneLink(todoLink);
                    doneLinkDAO.save(doneLink);
                    todoLinkDAO.delete(todoLink);
                    SysUser sendee = sysUserDAO.getOne(Long.parseLong(todoLink.getSendeeId()));
                    /*try {
                        todosCall.complete(todoLink.getLinkUrl(), sendee.getUserCode());
                        log.info("批量连接多米诺平台完成TODO[" + todoLink.getSubject() + "]成功");
                    } catch (RemoteException | UnsupportedEncodingException e) {
                        e.printStackTrace();
                        log.error("批量连接多米诺平台完成TODO[" + todoLink.getSubject() + "]失败", e);
                    }*/
                }
            }
        }
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void batchCreate(BatchCreateRequestDTO request) {
        if (request != null) {
            String[] sendeeIds = request.getSendeeIds();
            if (sendeeIds != null && sendeeIds.length > 0) {
                List<TodoLink> list = new ArrayList<>();
                for (String sendeeId : sendeeIds) {
                    TodoLink todolink = new TodoLink();
                    BeanUtils.copyProperties(request.getTodo(), todolink);
                    todolink.setSendeeId(sendeeId);
                    todolink.setCreatedTime(new Date());
                    list.add(todolink);
                }
                todoLinkDAO.saveAll(list);
            }
        }
    }
    //待办移交
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void changeToDone(String[] ids,String userId) {
        if (ids.length > 0) {
            for (String id : ids) {
                TodoLink todoLink = todoLinkDAO.getOne(Long.parseLong(id));
                SysUser user=sysUserDAO.getOne(Long.parseLong(userId));
                String userOrgFullName=user.fetchOrgFullName();
                String userName=user.getName();
                String OrgFullName=userName+"/"+userOrgFullName;
                System.out.println(OrgFullName);
                if (todoLink != null) {
                   // DoneLink doneLink = createDoneLink(todoLink);
                    todoLink.setSendeeId(userId);
                    String taskId=todoLink.getTaskId();
                    Todo todo=todoDAO.getOne(Long.parseLong(taskId));
                    todo.setExecutorId(userId);
                    todo.setExecutorName(OrgFullName);
                    todoDAO.save(todo);
                    todoLinkDAO.save(todoLink);
                }
            }
        }
    }

    //查询待办数量
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long getTodoCount(String userId) {
        Long ret=0l;
        ret=todoLinkDAO.getTodoCountByUserId(userId);
        return ret;
    }
}
